<template>
  <label>
    <span>
      <input
        type="checkbox"
        :disabled="disabled"
        :checked="currentValue"
        @change="change"
        :value="label"
        v-model="model"
        v-if="group"
      />
      <input type="checkbox" :disabled="disabled" :checked="currentValue" @change="change" v-else />
    </span>

    <slot></slot>
  </label>
</template>
<script>
import Emitter from "../../emitter";
import { findComponentUpward } from "../../utils/assist.js";
export default {
  name: "iCheckbox",
  mixins: [Emitter],
  data() {
    return {
      currentValue: this.value,
      group: false,
      model: [],
      parent: null
    };
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String, Number, Boolean],
      default: false
    },
    trueValue: {
      type: [String, Number, Boolean],
      default: true
    },
    falseValue: {
      type: [String, Number, Boolean],
      default: false
    },
    label: {
      type: [String, Number, Boolean]
    }
  },
  mounted() {
    this.parent = findComponentUpward(this, "iCheckboxGroup");
    if (this.parent) {
      this.group = true;
    }
    if (this.group) {
      // 拿到父组件的value
      this.parent.updateModel(true);
    } else {
      this.updateModel();
    }
  },
  watch: {
    value(val) {
      // 这里必须和trueValue或者falseValue值一同，否则不能同步到数据
      if (val === this.trueValue || val === this.falseValue) {
        this.updateModel();
      } else {
        throw "Value should be trueValue or falseValue.";
      }
    }
  },
  methods: {
    updateModel() {
      this.currentValue = this.value === this.trueValue;
    },
    change(event) {
      if (this.disabled) {
        return false;
      }
      // checked为true或者false
      const checked = event.target.checked;
      this.currentValue = checked;

      const value = checked ? this.trueValue : this.falseValue;
      this.$emit("input", value);
      this.$emit("on-change", value);
      
      if (this.group) {
        this.parent.change(this.model);
      } else {
        
        this.dispatch("iFormItem", "on-form-change", value);
        // this.dispatch("iCheckboxGroup", "on-form-change", value);
      }
    }
  }
};
</script>